var myWorkFlow = function()
{
    var lines = [],nodes=[];
    var defaults = {
        canDrag : false,
        recipe_id:'',
        rework_order_id:'',
        data_operate:[],
        data_devicetype:[],
        DbClickNode :null,
        DeleteClickNode:null,
        NodeDraggle:null,
        rework_order_id:''
    }
    this.initeInstance =function(options)
    {
        defaults = $.extend(defaults, options);
        instance =  jsPlumb.getInstance({
            Endpoint: ["Dot", {radius: 2}], //点的类型
            Connector: "Flowchart", //线的类型
            HoverPaintStyle: {stroke: "#7ab02c", strokeWidth: 2},//hover样式
            ConnectionOverlays: [  //箭头处的类型
                ["Arrow", {
                    location: 1,//arrow 与初始点的位置
                    id: "arrow", //arrow id
                    length: 10, //arrow 尺寸大小
                    foldback: 0.8 //箭头粗细度 值越小 arrow边缘越小
                }],
                ["Label", {
                    location: 0.5,
                    id: "label",
                    cssClass: "aLabel",
                    events: {
                        tap: function (e) {
                        }
                    }
                }]
            ],
            Container: "area" //必须为id
        });
        instance.registerConnectionType("basic", {anchor: "Continuous", connector: "Flowchart"});
        instance.bind("click", function (c, e) {
            if ($(e.target).attr("class") == "iconDiv") {
                if (deleteParamData()==1) {
                    instance.deleteConnection(c);
                }
            }
        });
        instance.bind("connection", function (info) { //划线停止后mouseUp触发事件
            info.connection.getOverlay("label").setLabel(function () {
                var iconDiv = '<div class="iconDiv" style="font-size: 20px;cursor: pointer;display: none">×</div>';
                return iconDiv;
            });
        });
        instance.batch(function () {
            //先清空
            $(".item_top_con").html('');
            $(".leftToolbar_top").html('');

            defaults.data_operate.forEach(function(d){
                var icon = 'fa fa-fire';
                var flag = 'operate_op';
                if(d.icon!=null)
                    icon = d.icon;
                if(d.type=="物料")
                {
                    flag = 'operate_mt';
                }
                var item = '<div class="item"><i class="'+ icon +'" style="margin-right: 3px;"></i><p>' + d.operateName + '</p><p style="display: none">'+ d.id +'</p><p style="display: none">'+ flag +'</p></div>';
                $(".item_top_con").append(item);
            })

            defaults.data_devicetype.forEach(function(d){
                var item = '<div class="item radiusItem"><p>'+ d.device_type_name+'</p><p style="display: none">'+ d.device_type_id +'</p><p style="display: none">deviceType</p></div>';
                $(".leftToolbar_top").append(item);
            })

            $(".basebtn .item").draggable({
                helper: "clone",//clone可以让你A 拖到B 并复制
                stop: function (e, ui) {
                    if(!defaults.canDrag)
                    {
                        return;
                    }

                    var left = parseInt(ui.offset.left - $(".area").offset().left);
                    var top = parseInt(ui.offset.top - $(".area").offset().top);
                    //拖动过来的元素   $(ui.helper).html()取 item 子级元素
                    var typeHtml = $(ui.helper).find("p").eq(2).html();
                    var ele;
                    if(typeHtml == "deviceType") //类别
                    {
                        ele = $('<div class="item item_type" ><div class="it1">' + $(ui.helper).html() + '<div class="ep ep1"></div><div class="ep ep2"></div><div class="ep ep3"></div><div class="ep ep4"></div></div></div>')
                    }
                    else if(typeHtml == "step") //步骤
                    {
                        var  botHtml = $(ui.helper).html();
                        ele = $('<div class="item item_step"><div class="it1">' + botHtml + '<div class="ep ep1"></div><div class="ep ep2"></div><div class="ep ep3"></div><div class="ep ep4"></div></div></div>')
                    }
                    else if(typeHtml == "img")  //开始结束
                    {
                        ele = $('<div class="item item_step"><div class="it1">' + $(ui.helper).html() + '<div class="ep ep1"></div><div class="ep ep2"></div><div class="ep ep3"></div><div class="ep ep4"></div></div></div>')
                    }
                    else if(typeHtml == "operate_op" || typeHtml =="operate_mt")
                    {
                        ele = $('<div class="item item_operate"><div class="it1">' + $(ui.helper).html() + '<div class="ep ep1"></div><div class="ep ep2"></div><div class="ep ep3"></div><div class="ep ep4"></div></div></div>')
                    }

                    if (ui.offset.left >= $(".area").offset().left) { //是否到拖放区域
                        ele.css({
                            "left": left,
                            "top": top,
                            position: "absolute",
                            margin: 0
                        });
                        $('.area').on("mouseenter", ".item .it1", function () {
                            $(this).children('.ep').css('display', 'block')
                        }).on("mouseleave", ".item .it1", function () {
                            $(this).children('.ep').css('display', 'none')
                        })
                        ele.find('.ep').css('display', 'none')
                        $(".area").append(ele);//拖动过来创建元素
                        initNode(ele);//调用方法
                    } else {
                        ele.remove();
                    }
                    var nodeData = {
                        id: $(ele).attr("id"),
                        name:  $(ui.helper).find("p").eq(0).html(),
                        operate_base_id: $(ui.helper).find("p").eq(1).html(),
                        type:$(ui.helper).find("p").eq(2).html()
                    };
                    //修复所有。当在中间区域拖动元素的时候，如果不带这一句，节点不会跟着元素一起移动。加上之后节点才会跟随标签移动。
                    jsPlumb.repaintEverything();
                    if(nodeData.type == "operate_op" || nodeData.type == "operate_mt")
                               defaults.NodeDraggle(nodeData);
                }
            });
        });


    }

    //保存
    this.save = function ()
    {
        var data = { lines: [], nodes: [] };
        var allLines = instance.getAllConnections();
        if (allLines.length != 0) {
            data.lines = getLines(allLines);
        } else {
            data.lines = lines = {};
        }
        data.nodes = getNodes();
        return data;
    }
    //加载
    this.loadNode = function (node)
    {
        var ele;
        if(node.node_type == "operate_mt" || node.node_type == "operate_op")
        {
            ele = $('<div class="item item_operate" id="'+ node.node_id+'"><div class="it1"><i class="fa '+ node.icon +'" style="margin-right: 3px;"></i><p>'+ node.node_name +'</p><p style="display: none">'+ node.node_operate_id+'</p><p style="display: none">'+ node.node_type+'</p><div class="ep ep1" style="display: none;"></div><div class="ep ep2" style="display: none;"></div><div class="ep ep3" style="display: none;"></div><div class="ep ep4" style="display: none;"></div></div></div>')
        }
        else if(node.node_type == "deviceType")
        {
            ele = $('<div class="item item_type" id="'+ node.node_id+'"><div class="it1"><p>'+ node.node_name +'</p><p style="display: none">'+ node.node_operate_id +'</p><p style="display: none">deviceType</p><div class="ep ep1" style="display: none;"></div><div class="ep ep2" style="display: none;"></div><div class="ep ep3" style="display: none;"></div><div class="ep ep4" style="display: none;"></div></div></div>')
        }
        else if(node.node_type  == "img")
        {
            var imgSrc = "";
            if(node.node_name == "开始")
            {
                imgSrc = "<img th:src=\"@{/self/flow/img/start.png}\">";
            }
            else if(node.node_name == "结束")
            {
                imgSrc = "<img th:src=\"@{/self/flow/img/end.png}\">";
            }
            ele = $('<div class="item item_step" id="'+ node.node_id+'"><div class="it1">'+ imgSrc+'<p>'+ node.node_name +'</p><p style="display: none">img</p><div class="ep ep1"></div><div class="ep ep2"></div><div class="ep ep3"></div><div class="ep ep4"></div></div></div>')
        }
        else if(node.node_type == "step")
        {
            ele = $('<div class="item item_step" id="'+ node.node_id+'"><div class="it1"><p>'+ node.node_name +'</p><p style="display: none">'+ node.node_operate_id +'</p><p style="display: none">step</p><div class="ep ep1" style="display: none;"></div><div class="ep ep2" style="display: none;"></div><div class="ep ep3" style="display: none;"></div><div class="ep ep4" style="display: none;"></div></div></div>')
        }
        ele.css({
                "left": node.left,
                "top": node.top,
                position: "absolute",
                margin: 0
            });
            $('.area').on("mouseenter", ".item .it1", function () {
                $(this).children('.ep').css('display', 'block')
            }).on("mouseleave", ".item .it1", function () {
                $(this).children('.ep').css('display', 'none')
            })
            $(".area").append(ele);
            initNode(ele);
    }
    this.loadLine = function (line)
    {
        instance.connect({ source: line.source, target: line.target, anchors: [line.source_anchor, line.target_anchor],paintStyle: line.style});
    }
    this.clearArea = function ()
    {
        $("#area").html("");
        instance.clear();
    }
    this.changeCanDrag = function(flag)
    {
        defaults.canDrag = flag;
    }
    var initNode = function (el) {
        instance.draggable(el, {containment: "parent"}); //限制拖动不超过父级边框
        instance.makeSource(el, {
            filter: ".ep",
            anchor: "Continuous",
            connectorStyle: {stroke: "#445566", strokeWidth: 2},
            connectionType: "basic",
            extract: {"action": "the-action"},
            maxConnections: -1,
            onMaxConnections: function (info, e) { //最大连接数
            }
        });
        instance.makeTarget(el, { //连线箭头指向的终点位置，如果注销，连接失败
            dropOptions: {hoverClass: "dragHover"},
            anchor: "Continuous",
            allowLoopback: false,//自己连自己
        });
    };
    var getNodes = function () {
        var nodes=[];
        $(".area .item").each(function () {
            nodes.push({
                node_id:$(this).attr("id"), //自动生成的id
                operate_base_id:$(this).find("p").eq(1).html(),
                node_name: $(this).find("p").html(),
                node_type:$(this).find("p").eq(2).html(),
                node_left: parseInt($(this).css("left")),
                node_top: parseInt($(this).css("top")),
                node_width: $(this).width(),
                node_height: $(this).height(),
                recipe_id:defaults.recipe_id,
                rework_order_id:defaults.rework_order_id
            })

        });
        return nodes;
    };
    var getLines = function (allLines) {
        var lineName;
        var lines = [];
        for (var i in allLines) {
            lineName = $("#" + allLines[i].getOverlay("label").canvas.id).find(".lineName").html();
            if(lineName == null)
                lineName = "";
            lines.push({
                line_id:allLines[i].id,
                line_name:lineName,
                source_id:allLines[i].sourceId,
                target_id:allLines[i].targetId,
                source_text:allLines[i].source.innerText,
                target_text:allLines[i].target.innerText,
                source_anchor:allLines[i].endpoints[0].anchor.type,
                target_anchor:allLines[i].endpoints[1].anchor.type

            })
        }
        return lines;
    }
    var operation = function () {
        $(".arrowBtn,.save").on("click", function () {//右侧弹窗收缩
            $(".area").find('.item').removeClass('clickState');
            $(".rightDiv").animate({right: -($(".rightDiv").outerWidth(true) + 10) + "px"}, 500, function () {
                index = 0;
            });
        });

        $(document).on("mouseenter", ".area .item", function () {
            if(!defaults.canDrag)
            {
                return;
            }
            var ele = $('<span>×</span>');//button 删除按钮
            ele.css({
                position: "absolute",
                left: "0",
                top: "-25px",
                width: 105 + "px",
                height: 55 + "px",
                textAlign: "left",
                lineHeight: 16 + "px",
                cursor: "pointer",
                fontSize: 20,
                display: "flex",
                alignItems: "center",
                justifyContent: "flex-end",
                paddingRight: "10px",
                zIndex: 0
            });
            $(this).append(ele);
        }).on("mouseleave", ".area .item", function () {
            $(this).find("span").remove();
        }).off('dblclick').on("dblclick", ".area .item", function (e) {
            if($(this).find("p").eq(2).html() == "operate_mt" || $(this).find("p").eq(2).html() == "operate_op")
            {
                 e.preventDefault();
                $(".area").find('.item').removeClass('clickState');
                 $(this).addClass("clickState");
                 var nodeData = {
                   id: $(this).attr("id"),
                   name:  $(this).find("p").eq(0).html(),
                   operate_base_id: $(this).find("p").eq(1).html(),
                   type:$(this).find("p").eq(2).html()
                };
                $(".rightDiv").animate({right: 0 + "px"}, 500, function () {
                 });
                defaults.DbClickNode(nodeData);
            }else if($(this).find("p").eq(2).html() == "step"){
                if(!defaults.canDrag)
                {
                    return;
                }
                var stepId = $(this).find("p").eq(0);
                var showId = stepId.html();
                //清空p标签里的值
                stepId.html("");
                $(this).find("input").remove();
                $(this).find(".it1").append("<input class='stepInput' value='"+ showId +"'/>");
                $(".stepInput").blur(function () {
                    var res = /^[1-9]\d*$/;//正整数
                    if (!res.test($(this).val())) {
                        layer.msg("步骤请输入正整数！");
                        stepId.html(showId);
                        $(this).remove();
                    }else{
                        //赋值输入的值
                        stepId.html($(this).val());
                        $(this).remove();
                    }

                });

            }

        }).off('click').on("click", ".area .item span", function () {
            if(!defaults.canDrag)
            {
                return;
            }

            var parentId = $(this).parent().attr("id");
            var parent = $(this).parent();
            swal({
                title: "您确定要删除吗",
                //text: "删除后将无法恢复，请谨慎操作！",
                type: "warning",
                showCancelButton: true,
                cancelButtonText: "取消",
                confirmButtonColor: "rgb(85 221 218)",
                confirmButtonText: "确定",
                closeOnConfirm: false
            }, function () {
                instance.removeAllEndpoints(parentId); //删除dom上所有点 官网detachAllConnections(el,[params]) 不好使
                parent.remove();
                swal.close();
                defaults.DeleteClickNode(parentId);
            })
        });
    };
    operation();
}